<?php

namespace app\common\model;

use think\Model;

class Attachment extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 定义字段类型
    protected $type = [
    ];

    public function setUploadtimeAttr($value)
    {
        return is_numeric($value) ? $value : strtotime($value);
    }

    /**
     * 删除上传文件
     *
     * @return void
     */
    public function delFile($url)
    {
        $attachmentFile = ROOT_PATH . '/public' . $url;
        if (is_file($attachmentFile)) {
            @unlink($attachmentFile);
        }
        return true;
    }

    public function getAbsolutePath($path)
    {
        if (preg_match('/^data:image\//', $path)) {
            return $path;
        }
        if (preg_match('/^http:\/\//', $path)) {
            return $path;
        }
        if (preg_match('/^https:\/\//', $path)) {
            return $path;
        }
        $request = request();
        $port = '';
        if ($request->server('SERVER_PORT') != '80') {
            $port = ':' . $request->server('SERVER_PORT');
        }
        return $request->server('REQUEST_SCHEME') . '://' . $request->server('SERVER_NAME') . $port . $path;
    }
    public static function getRelativePath($path) {
        if (!$path) {
            return $path;
        }
        if (preg_match('/^data:image\//', $path)) {
            return $path;
        }

        return preg_replace('/^https?:\/\/[\w\.]+/i', '', $path);
    }
    protected static function init()
    {
        // 如果已经上传该资源，则不再记录
        self::beforeInsert(function ($model) {
            if (self::where('url', '=', $model['url'])->find()) {
                return false;
            }
        });
    }
}
